import React from 'react'
import { useHistory } from 'react-router-dom'
import { Button, Form, Input, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useDispatch } from 'react-redux'
import { bindActionCreators } from 'redux'
import './index.less'
import LogoImage from '../../assets/logo.png'
// 这把所有的actions都导过来了
import { actionCreators } from '../../redux/actions'
import { login } from '../../app/login'

function Login () {
    const [form] = Form.useForm()
    // const token = useSelector((state) => state)
    const dispatch = useDispatch()
    // 想用哪个结构哪个
    const { loginAsync } = bindActionCreators(actionCreators,dispatch)
     // 编程式路由跳转
     const history = useHistory()
    // 表单校验规则
    const loginFormRules = {
      username:[
        {required: true,message: '用户名不能为空'},
        {min:3, max:10, message: '用户名长度在3~10个字符'}
      ],
      password:[
        {required: true,message: '密码不能为空'},
        {pattern:/^\w{6,18}$/, message: '密码长度在6~18个字符且不能包含非数字、英文字符', trigger:'blur'}
      ]
    }
    const onFinish = async (values) => {
      const { data, meta:{ status, msg } } = await login(values)
      if(status === 400) {
        return message.error(msg, 1)
      }
      if(status !== 200) {
        return message.error('登录失败，请稍后重试', 1)
      }
      const { token } = data
      loginAsync({token, isLogin: true})
      // 将token存在本地和容器内
      message.success('登录成功', 1)
      history.push('/')
    }

    const onFinishFailed = () => {
      message.error('用户名或者密码格式错误')
    }
    // 重置表单
    const onReset = () => {
      form.resetFields()
    }
      return (
        <div className="login-container">
          <div className="login-form">
            <div className="symbol-image">
              <img alt="logo图片" src={LogoImage} />
            </div>
            <Form
                form={form}
                initialValues={{
                  username: 'admin',
                  password: '123456'
                }}
                name="basic"
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
            >
            <Form.Item
                name="username"
                rules={loginFormRules.username}
            >
              <Input placeholder="请输入用户名" prefix={<UserOutlined style={{fontSize:'16px', color:'#ccc'}} />} />
            </Form.Item>

            <Form.Item
                name="password"
                rules={loginFormRules.password}
            >
              <Input.Password  placeholder="请输入密码" prefix={<LockOutlined style={{fontSize:'16px', color:'#ccc'}} />} />
            </Form.Item>
            <Form.Item span={24} style={{ textAlign: 'right' }}>
              <Button htmlType="submit" size="large" type="primary" >登 录</Button>
              <Button className="reset-btn" onClick={onReset} size="large" type="primary">重 置</Button>
            </Form.Item>
          </Form>
          </div>
        </div>
      )
}
export default Login